package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.util.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.TokenUtils;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-03-14
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private PatientService patientService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //查看用户的具体详细信息
    @Override
    public Map<String, Object> show(Long id) {
        HashMap<String, Object> map = new HashMap<>();
        UserInfo userInfo = baseMapper.selectById(id);
        map.put("userInfo", userInfo);

        List<Patient> patientList = patientService.findAll(id);
        map.put("patientList", patientList);
        return map;
    }

    //审批用户是否认证成功
    @Override
    public void updateAuthStatus(Integer id, Integer authStatus) {
        if (authStatus == -1 || authStatus == 2) {
            UserInfo userInfo = baseMapper.selectById(id);

            userInfo.setAuthStatus(authStatus);

            baseMapper.updateById(userInfo);
        } else {
            throw new YyghException(20001, "认证状态码错误");
        }
    }

    // 更改用户锁定或者正常的操作
    @Override
    public void updateStatus(Integer id, Integer status) {
        if (status == 0 || status == 1) {
            UserInfo userInfo = baseMapper.selectById(id);

            userInfo.setStatus(status);

            baseMapper.updateById(userInfo);
        } else {
            throw new YyghException(20001, "输入的状态码错误");

        }
    }

    @Override
    public IPage<UserInfo> selectPage(IPage<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        // 首先获取查询数据条件
        String keyword = userInfoQueryVo.getKeyword();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like("name", keyword);
            wrapper.like("phone", keyword);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }

        IPage<UserInfo> iPage = baseMapper.selectPage(userInfoPage, wrapper);
        List<UserInfo> records = iPage.getRecords();

        records.stream().forEach(item -> {
            this.packUserInfo(item);
        });
        return iPage;
    }


    private void packUserInfo(UserInfo item) {
        Map<String, Object> param = item.getParam();

        param.put("authStatusString", AuthStatusEnum.getStatusNameByStatus(item.getAuthStatus()));
        String statusString = item.getStatus() == 0 ? "锁定" : "正常";
        param.put("statusString", statusString);

    }

    // 根据openid判断当前客户是否存在
    @Override
    public UserInfo findUserInfoByOpenid(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    //实名认真
    @Override
    public void userAuth(UserAuthVo userAuthVo, Long userId) {

        // 然后根据id查询数据
        UserInfo userInfo = baseMapper.selectById(userId);

        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setName(userAuthVo.getName());
        userInfo.setAuthStatus(1);

        // 然后更新
        baseMapper.updateById(userInfo);

    }


    @Override
    public UserInfo getUserInfo(Long userId) {

        UserInfo userInfo = baseMapper.selectById(userId);
        return userInfo;
    }

    //会员登录
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        // 1.获取数据
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        // 2.进行数据校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "数据为空");
        }
        //TODO 3.发送验证码
        //校验校验验证码
        String mobleCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(mobleCode)) {
            throw new YyghException(20001, "验证码失败");
        }
        String openid = loginVo.getOpenid();


        if (StringUtils.isEmpty(openid)) {
            // 4.校验当前用户是否已经注册，若没注册直接注册在系统中
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);

            if (StringUtils.isEmpty(userInfo)) {
                // 给当前用户进行注册
                // 进行数据转换
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
            // 5.校验当前用户是否被禁用
            if (0 == userInfo.getStatus()) {
                throw new YyghException(20001, "当前用户已被禁用");
            }
            // 6.若已注册返回其数据参数
            HashMap<String, Object> map = this.getMessage(userInfo);
            return map;
        } else {
            // 我们需要绑定手机号
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            UserInfo userInfo = baseMapper.selectOne(wrapper);

            // 这里我们还需要判断当前数据库中是否存在手机号
            QueryWrapper<UserInfo> wrapperPhone = new QueryWrapper<>();
            wrapperPhone.eq("phone", phone);
            UserInfo userInfoPhone = baseMapper.selectOne(wrapperPhone);
            if (StringUtils.isEmpty(userInfoPhone)) {
                // 设置手机号
                userInfo.setPhone(phone);

                // 然后更新数据
                baseMapper.updateById(userInfo);

                // 然后返回数据
                HashMap<String, Object> map = this.getMessage(userInfo);
                return map;
            } else {
                userInfo.setPhone(userInfoPhone.getPhone());
                userInfo.setName(userInfoPhone.getName());
                userInfo.setCertificatesType(userInfoPhone.getCertificatesType());
                userInfo.setCertificatesNo(userInfoPhone.getCertificatesNo());
                userInfo.setCertificatesUrl(userInfoPhone.getCertificatesUrl());

                // 进行数据保存
                baseMapper.updateById(userInfo);

                // 然后删除原有数据
                baseMapper.deleteById(userInfoPhone.getId());

                // 然后返回数据
                HashMap<String, Object> map = this.getMessage(userInfo);
                return map;
            }


        }
    }

    public HashMap<String, Object> getMessage(UserInfo userInfo) {
        HashMap<String, Object> map = new HashMap<>();

        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }

        map.put("name", name);

        // todo
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }
}
